package com.lixw.jdbc.util;

import com.lixw.jdbc.core.annotation.TableField;
import com.lixw.jdbc.core.annotation.TableId;

import java.lang.reflect.Field;

/**
 * @ClassName: TableReflectUtils
 * @Description:
 * @Author: xuweiLi
 * @Create: 2025/5/30 17:24
 **/
public class TableReflectUtils {
    public static Field findByColumn(String labelName,Class<?> entityClass) throws NoSuchFieldException{
        Field[] declaredFields = entityClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            if(declaredField.isAnnotationPresent(TableField.class)){
                TableField annotation = declaredField.getAnnotation(TableField.class);
                String label = annotation.value();
                if(label.equals(labelName)){
                    return declaredField;
                }
            }else if(declaredField.getName().equals(labelName)){
                return declaredField;
            }
        }
        throw new NoSuchFieldException();
    }

    public static String findIdName(Class<?> entityClass) throws NoSuchFieldException{
        Field[] declaredFields = entityClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            if(declaredField.isAnnotationPresent(TableId.class)){
                TableId annotation = declaredField.getAnnotation(TableId.class);
                String idName = annotation.value();
                if(idName.isBlank()){
                    return declaredField.getName();
                }
                return idName;
            }
        }
        throw new NoSuchFieldException();
    }

}